package com.zeh.bill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zeh.bill.entity.Permission;
import com.zeh.bill.entity.User;
import com.zeh.bill.entity.Vo.PermissionQueryVo;
import com.zeh.bill.entity.Vo.RolePermissionVo;
import com.zeh.bill.mapper.PermissionMapper;
import com.zeh.bill.mapper.UserMapper;
import com.zeh.bill.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zeh.bill.untils.MenuTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zeh
 * @since 2022-07-18
 */
@Service
@Transactional
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private UserMapper usermapper;
    /**
     * 根据用户Id 查询权限列表
      * @param  userId
     * @return
     */
    @Override
    public List<Permission> findPermissionListByUserId(Long userId) {
        return baseMapper.findPermissionListByUserId(userId);
    }

    @Override
    public List<Permission> findPermissionList(PermissionQueryVo permissionQueryVo){
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("order_num");
        List<Permission> permissionList = baseMapper.selectList(queryWrapper);
        List<Permission> menuTree = MenuTree.makeMenuTree(permissionList, 0L);
        return menuTree;
    }

    /**
     * 查询上级菜单列表
     *
     */
    @Override
    public List<Permission> findParentPermissionList(){
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        //只查询type为目录和菜单的数据(type=0或type=1)
        queryWrapper.in("type", Arrays.asList(0,1))
        .orderByAsc("order_num");
        //查询菜单数据
        List<Permission> permissionList = baseMapper.selectList(queryWrapper);
        //构造顶级菜单信息，如果数据库中的菜单表没有数据，选择上级菜单时则显示顶级菜单
        Permission permission = new Permission();
        permission.setId(0L);
        permission.setParentId(-1L);
        permission.setLabel("顶级菜单");
        permissionList.add(permission);//将顶级菜单添加到集合
        //生成菜单数据
        List<Permission> menuTree = MenuTree.makeMenuTree(permissionList, -1L);
        return menuTree;
    }


    /**
     * 检查菜单是否有子菜单
     */
    @Override
    public boolean hasChildrenOfPermission(Long id){
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        if(baseMapper.selectCount(queryWrapper)>0){
            return true;
        }
        return false;
    }

    /**
     * 查询分配权限树列表
     * @param userId
     * @param roleId
     * @return
     */
    @Override
    public RolePermissionVo findPermissionTree(Long userId,Long roleId){
         //查询当前用户信息
        User user = usermapper.selectById(userId);
        List<Permission> list = null;
        //2.判断当前用户角色，如果是管理员，则查询所有权限；如果不是管理员，则只查询自己所拥有的的权限
        if(!ObjectUtils.isEmpty(user.getIsAdmin())&& user.getIsAdmin() == 1){
             list = baseMapper.selectList(null);
        }else{
            list = baseMapper.findPermissionListByUserId(userId);
        }
        List<Permission> PermissionTree = MenuTree.makeMenuTree(list, 0L); //生成权限树
        List<Permission> rolePermissions = baseMapper.findPermissionListByRoleId(userId); //查询要分配角色的原有权限
        List<Long> listIds = new ArrayList<>(); // 找出该角色存在的数据
        Optional.ofNullable(list).orElse(new ArrayList<>())
                .stream()
                .filter(Objects::nonNull) //等同于 obj -> obj != null
                .forEach(
                      item ->{
                          Optional.ofNullable(rolePermissions).orElse(new ArrayList<>())
                                  .stream()
                                  .filter(Objects::nonNull)
                          .forEach(
                                  obj ->{
                                      if(item.getId().equals(obj.getId())){
                                          listIds.add(obj.getId());
                                          return;
                                      }
                                  }
                          );
                      }
                );
        RolePermissionVo vo = new RolePermissionVo();
        vo.setPermissionList(PermissionTree);
        vo.setCheckList(listIds.toArray());
        return  vo;
    }
}
